package com.ry.day1129;


public class LC3598 {


      static class ListNode {
          int val;
          ListNode next;
          ListNode(int x) {
              val = x;
              next = null;
          }
      }


    static class Solution {
        /**
         * @param node1: The first ListNode
         * @param node2: The second ListNode
         * @return: A new linked list representing the sum of corresponding numbers in the two given linked lists.
         */
        public ListNode sumOfNumbers(ListNode node1, ListNode node2) {
            ListNode start = new ListNode(-1);
            ListNode end = start;

            boolean add = false;
            while (node1!=null && node2!=null){
                int c1 = node1.val;
                int c2 = node2.val;

                int sum = c1+c2;

                if(add) sum+=1;

                if(sum>=10) {
                    add= true;
                    sum=sum%10;
                }else{
                    add = false;
                }

                ListNode newNode = new ListNode(sum);
                end.next= newNode;
                end = newNode;

                node1 = node1.next;
                node2 = node2.next;
            }

            while (node1!=null){
                int sum = node1.val;


                if(add) sum+=1;

                if(sum>=10) {
                    add= true;
                    sum=sum%10;
                }else{
                    add = false;
                }

                ListNode newNode = new ListNode(sum);
                end.next= newNode;
                end = newNode;
                node1 = node1.next;

            }

            while (node2!=null){
                int sum = node2.val;


                if(add) sum+=1;

                if(sum>=10) {
                    add= true;
                    sum=sum%10;
                }else{
                    add = false;
                }

                ListNode newNode = new ListNode(sum);
                end.next= newNode;
                end = newNode;
                node2 = node2.next;

            }

            if(add){
                ListNode newNode = new ListNode(1);
                end.next= newNode;
            }

            return start.next;
        }


    }
}
